package com.ruoyi.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.Listener.DailyImportListener;
import com.ruoyi.domain.Dictionary;
import com.ruoyi.domain.ProcessRecord;
import com.ruoyi.domain.ProductionInfo;
import com.ruoyi.domain.RawmaterialInfo;
import com.ruoyi.service.DictionaryService;

import com.ruoyi.service.IProcessRecordService;

import com.ruoyi.service.RawmaterialInfoService;
import com.ruoyi.utils.EasyExcelConfig;
import com.ruoyi.utils.ExcelFillCellMergeStrategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 加工记录跟踪Controller
 *
 * @author ruoyi
 * @date 2024-02-28
 */
@RestController
@RequestMapping("/record")
public class ProcessRecordController extends BaseController
{
    @Autowired
    private IProcessRecordService processRecordService;

    @Autowired
    private RawmaterialInfoService rawmaterialInfoService;

    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 查询加工记录跟踪列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ProcessRecord processRecord)
    {
        startPage();
        List<ProcessRecord> list = processRecordService.selectProcessRecordList(processRecord);
        return getDataTable(list);
    }

    /**
     * 导出加工记录跟踪列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProcessRecord processRecord) throws IOException {
        Integer pageSize = 500;
        List<ProcessRecord> list = processRecordService.selectProcessRecordList(processRecord);
        /*ExcelUtil<ProcessRecord> util = new ExcelUtil<ProcessRecord>(ProcessRecord.class);
        util.exportExcel(response, list, "加工记录跟踪数据");*/
        //通过计算得出需要sheet的个数
        int sheetNum = list.size() % pageSize == 0 ? list.size() / pageSize : list.size() / pageSize + 1;
        List<ProcessRecord> prolist ;
        for (int i = 1; i <= sheetNum; i++) {
            if (i * pageSize - 1 <= list.size()) {
                prolist = list.subList((i - 1) * pageSize, i * pageSize - 1);
            } else {
                prolist = list.subList((i - 1) * pageSize, list.size());

            }

        response.setContentType(EasyExcelConfig.RESPONSE_TYPE);
        response.setCharacterEncoding(EasyExcelConfig.CHARSET);
//合并单元格 合并哪几列
        int[] mergeColumnIndex = {0};
        // 需要从第几行开始合并
        int mergeRowIndex = 1;
        EasyExcel.write(response.getOutputStream(), ProcessRecord.class)
                .autoCloseStream(Boolean.TRUE)
                .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumnIndex))
                .sheet("sheets" + i)
                .doWrite(prolist);
        }
    }

    /**
     * 获取加工记录跟踪详细信息
     */
    @GetMapping(value = "/{processId}")
    public AjaxResult getInfo(@PathVariable("processId") Long processId)
    {
        return success(processRecordService.selectProcessRecordByProcessId(processId));
    }

    /**
     * 新增加工记录跟踪
     */
    @PostMapping("add")
    public AjaxResult add(@RequestBody ProcessRecord processRecord)
    {
       String opertorName= dictionaryService.getNameById(processRecord.getOpertor());
       processRecord.setOpertor(opertorName);
        processRecord.setOperationTime(new Date());
        if (processRecord.getStress()!=null){
            processRecord.setStress(processRecord.getStress()+"Pa");
        }
        if (processRecord.getTemperature()!=null){
            processRecord.setTemperature(processRecord.getTemperature()+"℃");
        }
        if (processRecord.getHumidness()!=null){
            processRecord.setHumidness(processRecord.getHumidness()+"%RH");
        }
        return toAjax(processRecordService.insertProcessRecord(processRecord));
    }

    /**
     * 修改加工记录跟踪
     */
    @PutMapping
    public AjaxResult edit(@RequestBody ProcessRecord processRecord)
    {
        return toAjax(processRecordService.updateProcessRecord(processRecord));
    }

    /**
     * 删除加工记录跟踪
     */
	@DeleteMapping("/{processIds}")
    public AjaxResult remove(@PathVariable Long[] processIds)
    {
        return toAjax(processRecordService.deleteProcessRecordByProcessIds(processIds));
    }

    /**
     * 根据rawmaterial_id获取某一个农产品的所有加工信息
     */
@GetMapping("queryById")
    public List<ProcessRecord> queryById(Integer id){

    System.err.println(id);
    ProcessRecord processRecord = new ProcessRecord();
    processRecord.setRawmaterialId(Long.valueOf(id));
    List<ProcessRecord> list = processRecordService.selectProcessRecordList(processRecord);
    return list;
}






    HashMap<String, Long> rawmap = new HashMap<>();
    HashMap<String, Long> schmap = new HashMap<>();
    HashMap<String, Long> equipmap = new HashMap<>();
    @RequestMapping("importData")
    public AjaxResult importData(MultipartFile file) throws IOException{
        getmap();

        List<ProcessRecord> list = EasyExcel.read(file.getInputStream())
                // 注册监听器，可以在这里校验字段
                .registerReadListener(new DailyImportListener())
                .head(ProcessRecord.class)
                .sheet()
                .headRowNumber(1)
                .doReadSync();
        for (ProcessRecord processRecord : list) {
            //给RawmaterialId赋值
            String rawmaterialNum = processRecord.getRawmaterialNum();
            Long aLong = rawmap.get(rawmaterialNum);
            processRecord.setRawmaterialId(aLong);
            //给scheduleId赋值
            String scheduleName = processRecord.getScheduleName();
            Long aLong1 = schmap.get(scheduleName);
            processRecord.setScheduleId(aLong1);
            //给equipmentId赋值
            String equipmentName = processRecord.getEquipmentName();
            Long aLong2 = equipmap.get(equipmentName);
            processRecord.setEquipmentId(aLong2);
            System.err.println(processRecord);
        }
            //批量添加
        processRecordService.insertProductionInfoBatch(list);

        return success("导入成功");
    }

    public void getmap(){
        List<RawmaterialInfo> numList = rawmaterialInfoService.getNumList();
        for (RawmaterialInfo rawmaterialInfo : numList) {
            Long rawmaterialNum = rawmaterialInfo.getRawmaterialNum();
            Long id = rawmaterialInfo.getId();
            rawmap.put(rawmaterialNum+"",id );
        }
        List<Dictionary> typelist = dictionaryService.getStandardListByType("schedule_dic");
        for (Dictionary dictionary : typelist) {
            String name = dictionary.getName();
            Long dictValue = dictionary.getDictValue();
            schmap.put(name,dictValue);
        }
        List<Dictionary> equiptypelist = dictionaryService.getStandardListByType("equipment_dic");
        for (Dictionary dictionary : equiptypelist) {
            String name = dictionary.getName();
            Long dictValue = dictionary.getDictValue();
            equipmap.put(name,dictValue);
        }



    }
}
